#!/usr/bin/python

import sys, re, os, pickle
from time import gmtime, strftime


global userdict
global groupdict
global logged_in
global filedict
global currentuser
global is_admin

def main():
    if(not os.path.exists(sys.argv[1])):
        print 'The file you specified DNE.'
    else:
        cf = open(sys.argv[1], 'r')
        cmdstack = cf.readlines()
        cf.close()
        startup()        
    for cmd in cmdstack[:4]:
        parse_cmdline(cmd.replace('\n', ''))
        logged_in = False
        is_admin = False
    for cmd in cmdstack[4:]:
        parse_cmdline(cmd.replace('\n', ''))

def startup():
    global userdict
    global groupdict
    global logged_in
    global filedict
    global currentuser
    global is_admin
    logged_in = True
    is_admin = True
    userdict = {}
    currentuser = ''
    filedict = {}
    groupdict = {}
    groupdict['Users']=[]
    groupdict['Administrators']=[]
    
    if(os.path.exists('accounts.txt')):
        af = open('accounts.txt', 'r')
        for line in af.readlines():
            userdict[line[0:line.index(' ')]] = line[line.index(' ')+1:].replace('\n', '')
            groupdict['Users'].append(line[0:line.index(' ')])
        af.close()
    if(os.path.exists('audit.txt')):
        tmp = open('audit.txt', 'w+')
        tmp.close()
    print userdict
    print groupdict

def teardown():
    af = open('accounts.txt', 'w+')
    for u, p in userdict.iteritems():
        af.write(u+' '+p+'\n')
    af.close()
    gf = open('groups.txt', 'w+')
    for g, m in userdict.iteritems():
        gf.write(g+' '+m+'\n')
    gf.close()


def parse_cmdline(string):
    tokens = string.split()
    if(tokens[0] == 'login'):
        login_cmd(tokens[1], tokens[2])
    elif(logged_in == True):
        if(tokens[0] == 'logout'):
            logout_cmd()
        elif((tokens[0] == 'net')and(is_admin==True)):
            if(tokens[1] == 'user'):
                createUser(tokens[2], tokens[3])
            elif(tokens[1] == 'group'):
                if(len(tokens)==3):
                    createGroup(tokens[2])
                elif(len(tokens)==4):
                    group_addUser(tokens[2], tokens[3])
        elif(tokens[0]=='create'):
            makeFile(tokens[1])
        elif(tokens[0]=='read'):
            catFile(tokens[1])
        elif(tokens[0]=='write'):
            scribbleFile(tokens[1], ' '.join(tokens[2:]))
        elif(tokens[0]=='execute'):
            executeFile(tokens[1])
        elif(tokens[0]=='xcacls'):
            editPerms(tokens[1], tokens[2:])
    elif(tokens[0]=='end'):
        teardown()
        print 'end of instructions'
    else:
        print 'last option'

                    
def editPerms(filename, options):
    if(filename in filedict):
        if(('o' in filedict[filename][currentuser])or(currentuser in groupdict['Administrators'])):
            print 'options'
            print  options
            eflag = False
            if('/E' in options):
                editFlag = True
                print 'editPerms /E'
            if('/G' in options):
                grantAccess(filename,options.pop(), eflag)
                print 'editPerms /G'
            elif('/P' in options):
                replaceAccess(filename,options.pop(), eflag)
                print 'editPerm /P'
            elif('/D' in options):
                denyAccess(filename, options.pop(), eflag)
                print 'editPerms /D'


def grantAccess(filename, j, eflag):
    print j
    subject = j[0:j.index(':')]
    perms = j[j.index(':')+1:].lower().replace('f', 'rwx')
    if(subject in filedict[filename]):
        print 'User already has access'
        audit(currentuser+' attempted to grant '+subject+' access to '+filename)
    else:
        if(eflag):
            filedict[filename][subject]=perms
        else:
            filedict[filename][subject]=perms


def replaceAccess(filename, options, eflag):
    filedict[filename][subject]=perms
    print 'replace access'

def denyAccess(filename, options,  eflag):
    print 'deny access'

def login_cmd(uname, passwd):
    global logged_in
    global currentuser
    if(logged_in == False):
        if(uname in groupdict['Users']):
            if(userdict[uname] == passwd):
                currentuser = uname
                logged_in = True
                if(currentuser in groupdict['Administrators']):
                    is_admin = True
                audit(uname+'; logged in.')
                print uname+'; logged in.'
            else:
                audit(uname+' attempted to login. Authentication error.')
        else:
            audit(uname+' failed login attempt. Not a user.')
            print 'Login failed.'
            logged_in = False
    else:
        audit(currentuser+' attempted to login as '+uname)
        print 'You cannot login if another user is already logged in.'


def logout_cmd():
    logged_in = False
    is_admin = False
    currentuser = ''

##create file command
def makeFile(filename):
    if(filename not in filedict):
        tmpF = open(filename, 'w+')
        tmpF.close()
        if(currentuser in groupdict['Administrators']):
            for user in groupdict['Users']:
                filedict[filename][user]=['r']
            for user in groupdict['Administrators']:
                filedict[filename][user]=['r','w','x']
            filedict[filename]={currentuser:['r','w','x','o']}
        else:
            filedict[filename]={currentuser:['r','w','x','o']}
        audit(filename+' created by '+currentuser)
    else:
        audit(currentuser+' attempted file creation.'+filename+' already exists')
        print 'File already exists'


def catFile(filename):
    if(filename not in filedict):
        audit(currentuser+' attempted to view file that DNE')
        print 'can\'t read file. DNE.'
    elif(currentuser in filedict[filename]):
        if('r' in filedict[filename][currentuser]):
            tmpf = open(filename,'r')
            print tmpf.read()
            tmpf.close()

def scribbleFile(filename, text):
    if(filename in filedict):
        if(currentuser in filedict[filename]):
            if('w' in filedict[filename][currentuser]):
                tmpf = open(filename, 'a')
                tmpf.write(text)
                tmpf.close()
            else: 
                audit(currentuser+' attempted to write to '+filename+' without permission')
        else: 
            audit(currentuser+' attempted to write to '+filename+' without access')
    else:
        print filename+' DNE.'
        audit(currentuser+' attempted to write to a file '+filename+' that DNE.')


def executeFile(filename):
    if(filename in filedict):
        if(currentuser in filedict[filename]):
            if('x' in filedict[filename][currentuser]):
                audit(currentuser+' executed '+filename+' successfully.')
                print 'successful program execution'
            else:
                audit(currentuser+' attempted to execute '+filename+'. Permission denied')
                print 'failed program execution by '+currentuser
        else:
            audit(currentuser+' attempted to execute '+filename+'. No access')
    else:
        audit(currentuser+' execute failed. '+filename+' DNE')

##su commands
def createGroup(gname):
    if(gname in groupdict):
        print 'Groupname is already in use. Please choose another.'
    else:
        groupdict[gname] = []
        
def group_addUser(gname, uname):
    if(gname in groupdict):
        if(uname not in groupdict[gname]):
            groupdict[gname].append(uname)
        else: print 'User is already member of group.'
    else:
        print 'You must first create the group before populating it.'


def createUser(uname, passwd):
    if(uname in userdict):
        print 'Username is already in use. Please choose another.'
    else:
        userdict[uname] = passwd
        nu = {uname:'r'}
        groupdict['Users']

##end su commands

def audit(stuff):
    auditFile = open('audit.txt', 'a')
    auditFile.write(timestamp()+'\t'+stuff+'\n')

def timestamp():
        return strftime("%Y-%m-%d %H:%M:%S", gmtime())


class User:
    def  __init__(self, uname):
        self.u = uname


if __name__ == '__main__':
    main()
